local DataModel = class("DataModel")

function DataModel:ctor()
	self._listeners={}
end

function DataModel:update(name,data,dispatchEvent)
	local old = self[name]
	local new
	if type(data)=="table" then
		new = data[name]
	else
		new = data
	end
	--print("===>DataModel update ",name,"old",old,"new",new)
	if type(new)~="nil" then
		self[name] = new
		if old~=new and dispatchEvent then
			self:dispatchChange(name,old,new)
		end
	end
end

function DataModel:onChanged(listener)
	local handle = #self._listeners + 1
	self._listeners[handle]=listener
	return handle
end

function DataModel:unChanged(handle)
	self._listeners[handle]=nil
end

function DataModel:dispatchChange(...)
	for _,listener in pairs(self._listeners) do
		if listener then
			listener(...)
		end
	end
end


return DataModel